# -*- coding: UTF-8 -*-
import logging
import sys
import traceback
from logging.handlers import RotatingFileHandler
from pathlib import Path


def init_logging(logger_name, logger=None):
    current_dir = Path(__file__).resolve().parent.parent
    if logger is None:
        logger = logging.getLogger(logger_name)
    formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s File [%(filename)s] '
        'in [%(funcName)s] [line:%(lineno)d] %(message)s')
    logs_dir = current_dir / 'logs'
    logs_dir.mkdir(parents=True, exist_ok=True)

    error_log = logs_dir / f'{logger_name}_err.log'
    info_log = logs_dir / f'{logger_name}_info.log'

    error_file_handler = RotatingFileHandler(
        error_log,
        maxBytes=512 * 1024 * 1024,
        backupCount=2
    )
    error_file_handler.setLevel(logging.ERROR)
    error_file_handler.setFormatter(formatter)
    logger.addHandler(error_file_handler)

    info_file_handler = RotatingFileHandler(
        info_log,
        maxBytes=512 * 1024 * 1024,
        backupCount=2
    )
    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(formatter)
    logger.addHandler(info_file_handler)
    logger.setLevel(logging.DEBUG)
    return logger


def format_exc_all():
    exc_type, exc_obj, tb = sys.exc_info()
    # 检查是否有异常
    if exc_obj is None:
        return "No exception found."
    # 提取异常的堆栈信息
    excepts = traceback.extract_tb(tb)
    # 初始化返回值
    rets = ''
    glue = ''
    # 遍历堆栈并格式化输出
    for exc in excepts:
        filename, lineno, funname, line = exc
        rets += glue + \
                '{}:{}, in {}    {}  {}'.format(
                    filename, lineno, funname, line, str(exc_obj))
        glue = ' | '
    return "[%s]" % rets
